from math import log
import operator

## 注意：这里没有用到基尼系数；基于ID3

## 这的熵就是信息增益：在划分数据集之前之后信息发生的变化
## 用来计算给定数据集的熵
def calcShannonEnt(dataSet):
    numEntries = len(dataSet)
    labelCounts = {}
    for featVec in dataSet:
        currentLabel = featVec[-1] # 获取每一行的标签
        if currentLabel not in labelCounts.keys():
            labelCounts[currentLabel] = 0 # 如果没有这个标签就创建一个
        labelCounts[currentLabel] += 1
    shannonEnt = 0.0
    for key in labelCounts:
        prob = float(labelCounts[key]) / numEntries
        shannonEnt -= prob * log(prob, 2)
    return shannonEnt

## 产生数据集
def createDataSet():
    dataSet = [[1, 1, 'yes'], 
            [1, 1, 'yes'], 
            [1, 0, 'no'], 
            [0, 1, 'no'], 
            [0, 1, 'no']]
    labels = ['no surfacing', 'flippers']
    return dataSet, labels

## 按给定特征划分数据集
def splitDataSet(dataSet, axis, value): # 待划分的数据集，特征(这里的特征用数据集的索引输入)，特征的返回值
    retDataSet = []
    for featVec in dataSet:
        if featVec[axis] == value:
            reducedFeatVec = featVec[:axis]
            reducedFeatVec.extend(featVec[axis + 1:]) # extend一次性追加另一个序列中的多个值
            retDataSet.append(reducedFeatVec)
    return retDataSet # 这里返回的是将这个特征输入后筛选然后删除这个特征的结果


## 选择最好的数据集划分方式
## 数据要求：数据必须是一种由列表元素组成的列表，所有的列表元素有相同的数据长度；数据最后一列的最后一个元素是当前实例的类别标签
def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1  # 得到总共有多少个特征
    baseEntropy = calcShannonEnt(dataSet) # 计算总的熵
    bestInfoGain = 0.0
    bestFeature = -1
    for i in range(numFeatures):
        featList = [example[i] for example in dataSet]
        uniqueVals = set(featList) # 存入所有的可能的特征值
        newEntropy = 0.0
        for value in uniqueVals:
            subDataSet = splitDataSet(dataSet, i, value)
            prob = len(subDataSet) / float(len(dataSet))
            newEntropy += prob * calcShannonEnt(subDataSet)
        infoGain = baseEntropy - newEntropy
        if (infoGain > bestInfoGain): # 这里计算出每一个特征排除之后的熵，如果最小就选为最佳信息增益
            bestInfoGain = infoGain
            bestFeature = i
    return bestFeature # 计算最好的信息增益

## 返回出现次数最多的分类名称
def majorityCnt(classList):
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys():
            classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


## 创建树的函数代码
def createTree(dataSet, labels):
    classList = [example[-1] for example in dataSet]
    if classList.count(classList[0]) == len(classList): # 类别完全相同则停止继续划分，也就是说分到一定程度出现了其他标签全部为相同值
        return classList[0]
    if len(dataSet[0]) == 1:  # 遍历完所有特征时返回出现次数最多的
        return majorityCnt(classList)
    bestFeat = chooseBestFeatureToSplit(dataSet) ## 在数据集中选出最佳特征
    bestFeatLabel = labels[bestFeat]
    myTree = {bestFeatLabel: {}}
    del(labels[bestFeat])
    featValues = [example[bestFeat] for example in dataSet]
    uniqueVals = set(featValues) # 得到最佳特征的所有值
    for value in uniqueVals:
        subLabels = labels[:] # 取出所有的出去最佳特征的标签
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
    return myTree

## 使用决策树的分类函数
def classify(inputTree, featLabels, testVec):
    firstStr = list(inputTree.keys())[0]
    secondDict = inputTree[firstStr]
    featIndex = featLabels.index(firstStr)
    for key in secondDict.keys():
        if testVec[featIndex] == key:
            if type(secondDict[key]).__name__ == 'dict':
                classLabel = classify(secondDict[key], featLabels, testVec)
            else:
                classLabel = secondDict[key]
    return classLabel

## 存储生成的决策树
def storeTree(inputTree, filename):
    import pickle
    with open(filename, 'w') as fw:
        pickle.dump(inputTree, fw)

## 取回文件中的决策树
def grabTree(filename):
    import pickle
    with open(filename) as fr:
        return pickle.load(fr)
